package com.mac.hosp_pre.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.mac.hosp_pre.admin.service.DepartmentService;
import com.mac.hosp_pre.admin.entity.Department;
import com.mac.hosp_pre.except.ResultCodeEnum;
import com.mac.hosp_pre.except.ServiceException;
import com.mac.hosp_pre.admin.model.req.DeptQueryReqDto;
import com.mac.hosp_pre.admin.model.req.DeptReqDto;
import com.mac.hosp_pre.admin.model.resp.DeptRespDto;
import com.mac.hosp_pre.admin.model.resp.DeptTreeRespDto;
import com.mac.hosp_pre.reply.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DepartmentServiceImpl extends BaseMongoServiceImpl<Department> implements DepartmentService {
    @Override
    public void add(DeptReqDto req) {
        if (StringUtils.isAnyBlank(req.getHospCode(), req.getDeptCode())){
            throw new ServiceException(ResultCodeEnum.PARAM_EMPTY_ERROR.getCode(),"医院编号和科室编号不能为空");
        }
        Department dept = new Department();
        dept.setHospCode(req.getHospCode());
        dept.setDeptCode(req.getDeptCode());
        Department one = super.findOne(dept);
        //判断
        if(Objects.nonNull(one)) {
            one.setUpdateTime(new Date());
            one.setDeleted(false);
            super.updateById(one.getId(),one);
        } else {
            Department entity = new Department();
            BeanUtils.copyProperties(req,entity);
            Date date = new Date();
            entity.setCreateTime(date);
            entity.setUpdateTime(date);
            entity.setDeleted(false);
            super.save(entity);
        }
    }

    @Override
    public PageResult<DeptRespDto> findPageDepartment(DeptQueryReqDto deptQuery) {
        // 创建Pageable对象，设置当前页和每页记录数
        PageRequest pageable = PageRequest.of(deptQuery.getPageNo()-1,deptQuery.getPageSize(),Sort.by(Sort.Direction.DESC,"updateTime"));
        // 创建对象
        Department department = new Department();
        BeanUtils.copyProperties(deptQuery,department);
        PageResult<Department> pageResult = super.findPageByCondition(pageable, department);
        if (CollectionUtil.isNotEmpty(pageResult.getList())){
            List<DeptRespDto> deptTreeRespDtoList = pageResult.getList().stream().map(item -> {
                DeptRespDto deptResp = new DeptRespDto();
                BeanUtils.copyProperties(item,deptResp);
                return deptResp;
            }).collect(Collectors.toList());
            return new PageResult<>(deptTreeRespDtoList,pageResult.getTotal(),pageResult.getPageSize(),pageResult.getPageNo());
        }
        return PageResult.empty();
    }

    @Override
    public void remove(String hospCode, String deptCode) {
        if (StringUtils.isAnyBlank(hospCode, deptCode)){
            throw new ServiceException(ResultCodeEnum.PARAM_EMPTY_ERROR.getCode(),"医院编号和科室编号不能为空");
        }
        //根据医院编号 和 科室编号查询
        Query query = new Query();
        query.addCriteria(Criteria.where("hospCode").is(hospCode).and("deptCode").is(deptCode));
        Department department = super.findOne(query);
        if(department != null) {
            //调用方法删除
            super.deleteById(department.getId());
        }
    }

    @Override
    public List<DeptTreeRespDto> findDeptTree(String hospCode) {
        //创建list集合，用于最终数据封装
        List<DeptTreeRespDto> result = new ArrayList<>();

        //根据医院编号，查询医院所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHospCode(hospCode);
        //所有科室列表 departmentList
        List<Department> departmentList = super.findByCondition(departmentQuery);
        if (CollectionUtil.isEmpty(departmentList)){
            return result;
        }

        //根据大科室编号  bigcode 分组，获取每个大科室里面下级子科室
        Map<String, List<Department>> deparmentMap =
                departmentList.stream().collect(Collectors.groupingBy(Department::getBigCode));
        //遍历map集合 deparmentMap
        for(Map.Entry<String,List<Department>> entry : deparmentMap.entrySet()) {
            //大科室编号
            String bigCode = entry.getKey();
            //大科室编号对应的全局数据
            List<Department> deptList = entry.getValue();
            //封装大科室
            DeptTreeRespDto deptOne = new DeptTreeRespDto();
            deptOne.setDeptCode(bigCode);
            deptOne.setDeptName(deptList.get(0).getBigName());

            //封装小科室
            List<DeptTreeRespDto> children = new ArrayList<>();
            for(Department department : deptList) {
                DeptTreeRespDto deptTwo =  new DeptTreeRespDto();
                deptTwo.setDeptCode(department.getDeptCode());
                deptTwo.setDeptName(department.getDeptName());
                //封装到list集合
                children.add(deptTwo);
            }
            //把小科室list集合放到大科室children里面
            deptOne.setChildren(children);
            //放到最终result里面
            result.add(deptOne);
        }
        //返回
        return result;
    }

    @Override
    public String getDepName(String hospCode, String deptCode) {
        if (StringUtils.isAnyBlank(hospCode, deptCode)){
            throw new ServiceException(ResultCodeEnum.PARAM_EMPTY_ERROR.getCode(),"医院编号和科室编号不能为空");
        }
        //根据医院编号 和 科室编号查询
        Query query = new Query();
        query.addCriteria(Criteria.where("hospCode").is(hospCode).and("deptCode").is(deptCode));
        Department department = super.findOne(query);
        if(department != null) {
            return department.getDeptName();
        }
        return null;
    }

    @Override
    public DeptRespDto getDepartment(String hospCode, String deptCode) {
        if (StringUtils.isAnyBlank(hospCode, deptCode)){
            throw new ServiceException(ResultCodeEnum.PARAM_EMPTY_ERROR.getCode(),"医院编号和科室编号不能为空");
        }
        //根据医院编号 和 科室编号查询
        Query query = new Query();
        query.addCriteria(Criteria.where("hospCode").is(hospCode).and("deptCode").is(deptCode));
        Department department = super.findOne(query);
        if(department != null) {
            DeptRespDto target = new DeptRespDto();
            BeanUtils.copyProperties(department,target);
            return target;
        }
        return null;
    }
}
